package edu.scut.course_management.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import edu.scut.course_management.dto.NewHomeworkDTO;
import edu.scut.course_management.dto.RequestForHCOStudentDTO;
import edu.scut.course_management.dto.RequestForHCOTeacherDTO;
import edu.scut.course_management.dto.SHBriefInfoDTO;
import edu.scut.course_management.dto.SHDetailInfoDTO;
import edu.scut.course_management.dto.SectionPlusStudentIdDTO;
import edu.scut.course_management.dto.StatisticsDTO;
import edu.scut.course_management.dto.SubmitHomeworkDTO;
import edu.scut.course_management.exception.CustomException;
import edu.scut.course_management.po.Answer;
import edu.scut.course_management.po.Attachment;
import edu.scut.course_management.po.Homework;
import edu.scut.course_management.po.Section;
import edu.scut.course_management.po.SectionHomework;
import edu.scut.course_management.result.JsonResult;
import edu.scut.course_management.result.JsonResultFactory;
import edu.scut.course_management.result.ResultCode;
import edu.scut.course_management.service.HomeworkManagementService;

/**
 * 作业管理模块
 */

@RestController
@RequestMapping("Homework")
public class HomeworkManagementController {
    
    @Autowired HomeworkManagementService homeworkManagementService;

    /**
     * 发布作业
     * url：http://localhost:8080/Homework/Publish
     * @param newHomeworkDTO
     * @return
     */
    @PostMapping("/Publish")
    public JsonResult publishHomework(@RequestBody NewHomeworkDTO newHomeworkDTO) {
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();

        // 先对dto对象做非空检验 如果有字段为空直接返回
        if (!newHomeworkDTO.notNull()) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }

        Homework homeworkTemp = null;
        // 从dto对象中取出homework的需要字段，可能会在时间类型转换有异常
        try {
            homeworkTemp = newHomeworkDTO.getHomework();
        } catch (CustomException exception) {
            jsonResult = jsonResultFactory.buildFailResult(exception.getResultCode());
            return jsonResult;
        }

        // 从dto对象中取出section_homework需要的字段，这里是缺省了homeowork_id字段的
        SectionHomework sectionHomework = newHomeworkDTO.getSectionHomework();
        // 从dto对象中取出attachment的多个对象
        List<Attachment> attachmentList = newHomeworkDTO.getAttachmentList();
        // 从dto对象中取出section对象
        List<Section> sections = newHomeworkDTO.getSectionList();
        try {
            homeworkManagementService.addAllOfPublish(homeworkTemp, sectionHomework,
                attachmentList, sections);
        } catch (CustomException e ) {
            jsonResult = jsonResultFactory.buildFailResult(e.getResultCode());
        }
        jsonResult = jsonResultFactory.buildSuccessResult();
        return jsonResult;        
    }

    /**
     * 查看单个作业信息（教师）
     * url: http://localhost:8080/Homework/queryHomeworkCondition
     * @param homeworkId
     * @return
     */
    @PostMapping("/queryHomeworkCondition")
    public JsonResult queryHomeworkForTeacher(@RequestBody Map<String,Integer>map) {
        Integer homeworkId = map.get("homeworkId");
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (homeworkId == null) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        List<SHBriefInfoDTO> shBriefInfoDTOs = homeworkManagementService.findAllSHBriefInfoByHomeworkId(homeworkId);
        jsonResult = jsonResultFactory.buildSuccessResult(shBriefInfoDTOs);
        return jsonResult;
    }

    /**
     * 查看单个作业信息（学生）
     * url:http://localhost:8080/Homework/queryWorkConditionOfS
     */
    @PostMapping("/queryWorkConditionOfS")
    public JsonResult queryHomeworkForStudent(@RequestBody Map map) {
        Integer homeworkId = (Integer) map.get("homeworkId");
        String studentId = (String) map.get("studentId");
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        SHDetailInfoDTO shDetailInfoDTO = new SHDetailInfoDTO();

        Answer answerTemp = homeworkManagementService.findAnswerByHomeworkIdAndStudentId(homeworkId, studentId);
        shDetailInfoDTO.setAnswerContent(answerTemp.getAnswerContent());
        
        shDetailInfoDTO.setScore(null);

        Homework homework = homeworkManagementService.findHomeworkByHomeworkId(homeworkId);
        shDetailInfoDTO.setHomeworkTitle(homework.getHomeworkTitle());
        shDetailInfoDTO.setHomeworkContent(homework.getHomeworkContent());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        shDetailInfoDTO.setDeadline(dateFormat.format(homework.getDeadline()));
        List<Attachment> homeworkAttachments = homeworkManagementService.findAttachmentsByHomeworkId(homeworkId);
        shDetailInfoDTO.setHomeworkAttachmentList(homeworkAttachments);
        
        List<Attachment> answerAttachments = homeworkManagementService.findAttachmentsByAnswerId(answerTemp.getAnswerId());
        shDetailInfoDTO.setAnswerAttachmentList(answerAttachments);
        
        // 以下是检验作业的状态
        if (answerTemp.getIsCheck()) {
            shDetailInfoDTO.setIsCheck("已批改");
            shDetailInfoDTO.setScore(answerTemp.getScore());
        } else if (answerAttachments == null || answerAttachments.size() == 0 && answerTemp.getAnswerContent() == "") {
            shDetailInfoDTO.setIsCheck("未提交");
        } else {
            shDetailInfoDTO.setIsCheck("未批改");
        }

        jsonResult = jsonResultFactory.buildSuccessResult(shDetailInfoDTO);
        return jsonResult;
    }

    /**
     * 查询课程作业列表（教师）
     * url: http://localhost:8080/Homework/queryWorkListOfT
     */
    @PostMapping("/queryWorkListOfT")
    public JsonResult queryHomeworkListOfTeacher(@RequestBody Section section) {
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (!homeworkManagementService.sectionNotNull(section)) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        List<Homework> homeworks = homeworkManagementService.findHomeworkBySection(section);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<RequestForHCOTeacherDTO> requestForHCOTeacherDTOs = new ArrayList<>();
        for (Homework each: homeworks) {
            RequestForHCOTeacherDTO temp = new RequestForHCOTeacherDTO();
            temp.setDeadline(dateFormat.format(each.getDeadline()));
            temp.setPublishTime(dateFormat.format(each.getPublishTime()));
            temp.setHomeworkContent(each.getHomeworkContent());
            temp.setHomeworkId(each.getHomeworkId());
            temp.setHomeworkTitle(each.getHomeworkTitle());
            requestForHCOTeacherDTOs.add(temp);
        }
        jsonResult = jsonResultFactory.buildSuccessResult(requestForHCOTeacherDTOs);
        return jsonResult;
    }

    /**
     * 查询课程作业列表（学生）
     * url: http://localhost:8080/Homework/queryWorkListOfS
     * @param sectionPlusStudentIdDTO
     * @return
     */
    @PostMapping("/queryWorkListOfS")
    public JsonResult queryHomeworkListForStudent(@RequestBody SectionPlusStudentIdDTO sectionPlusStudentIdDTO) {
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (!sectionPlusStudentIdDTO.notNull()) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        List<RequestForHCOStudentDTO> requestForHCOStudentDTOs = homeworkManagementService.findSADetailInfosBySectionPStudentId(sectionPlusStudentIdDTO);
        jsonResult = jsonResultFactory.buildSuccessResult(requestForHCOStudentDTOs);
        return jsonResult;
    }

    /**
     * 提交作业
     * url: http://localhost:8080/Homework/sendingWork
     * @param submitHomeworkDTO
     * @return
     */
    @PostMapping("sendingWork")
    public JsonResult sendingHomework(@RequestBody SubmitHomeworkDTO submitHomeworkDTO) {
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (!submitHomeworkDTO.notNull()) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        Answer answer = homeworkManagementService.findAnswerByHomeworkIdAndStudentId(submitHomeworkDTO.getHomeworkId(), 
                    submitHomeworkDTO.getStudentId());
        // 如果老师已经批改就无法再提交作业
        if (answer.getIsCheck()) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.ALREADY_CORRECTED_CANNOT_SUBMIT_AGAIN);
            return jsonResult;
        }
        try {
            homeworkManagementService.updateAllAboutSending(submitHomeworkDTO);
        } catch(CustomException e) {
            jsonResult = jsonResultFactory.buildFailResult(e.getResultCode());
            return jsonResult;
        }
        jsonResult = jsonResultFactory.buildSuccessResult();
        return jsonResult;
    }

    /**
     * 批改作业
     * url:http://localhost:8080/Homework/workCorrecting
     * @param homeworkId
     * @param studentId
     * @param score
     * @param teacherReply
     * @return
     */
    @PostMapping("workCorrecting")
    public JsonResult homeworkCorrecting(@RequestBody Map map) {
        Integer homeworkId = (Integer) map.get("homeworkId");
        String studentId = (String) map.get("studentId");
        Integer score = (Integer) map.get("score");
        JsonResult jsonResult = null;
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (homeworkId==null || studentId==null || score==null) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        Answer answer = homeworkManagementService.findAnswerByHomeworkIdAndStudentId(homeworkId, studentId);
        if (answer.getIsCheck()) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.ALREADY_CORRECTED_CANNOT_CORRECT_AGAIN);
            return jsonResult;
        }
        try {
            homeworkManagementService.updateCorrectingContent(homeworkId, studentId, score);
        } catch(CustomException e) {
            jsonResult = jsonResultFactory.buildFailResult(e.getResultCode());
            return jsonResult;
        }
        jsonResult = jsonResultFactory.buildSuccessResult();
        return jsonResult;
    }


    /**
     * 查看学生作业统计情况
     * url:http://localhost:8080/Homework/statistics
     * @param map
     * @return
     */
    @PostMapping("statistics")
    public JsonResult getHomeworkStatistics(@RequestBody Map map) {
        JsonResult jsonResult = null;
        Integer homeworkId = (Integer) map.get("homeworkId");
        JsonResultFactory jsonResultFactory = JsonResultFactory.getInstance();
        if (homeworkId == null) {
            jsonResult = jsonResultFactory.buildFailResult(ResultCode.PARAM_IS_BLANK);
            return jsonResult;
        }
        StatisticsDTO statisticsDTO = homeworkManagementService.getStatistics(homeworkId);
        jsonResult = jsonResultFactory.buildSuccessResult(statisticsDTO);
        return jsonResult;
    }
}
